package com.dji.compose_learning.ui.view

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.dji.compose_learning.todolist.TodoIcon
import com.dji.compose_learning.todolist.TodoItem
import com.dji.compose_learning.todolist.TodoListViewModel
import com.dji.compose_learning.ui.theme.Compose_learningTheme
import com.dji.compose_learning.utils.viewModel
import kotlin.random.Random


@Composable
fun TodoListPage(addItem: () -> Unit) {
    Compose_learningTheme {
        Surface(modifier = Modifier.fillMaxWidth(),
            color = MaterialTheme.colorScheme.background) {
            Column {
                val viewModel = viewModel<TodoListViewModel>()
                val todolist by viewModel.todolist.observeAsState(listOf())
                var editorMode by remember {
                    mutableStateOf(false)
                }
                var editTodoItem by remember {
                    mutableStateOf<TodoItem?>(null)
                }
                TodoItemAdder(editorMode = editorMode, modifier = Modifier.wrapContentHeight())
                LazyColumn(modifier = Modifier.weight(1f),
                    contentPadding = PaddingValues(top = 8.dp)) {
                    items(todolist.size) { it ->
                        TodoRow(item = todolist[it],
                            editorMode = editTodoItem == todolist[it],
                            modifier = Modifier.fillParentMaxWidth(),  //这里填充父容器的最大宽度，使item和屏幕同宽
                            editItem = {
                                editorMode = true
                                editTodoItem = it
                            },
                            updateItem = {
                                editorMode = false
                                editTodoItem = null
                            },
                            deleteItem = {
                                editorMode = false
                                editTodoItem = null
                                viewModel.removeItem(it)
                            }
                        )
                    }
                }

                Button(onClick = addItem, modifier = Modifier
                    .padding(16.dp)
                    .fillMaxWidth()) {
                    Text(text = "Add random item")
                }
            }
        }
    }
}

/**
 * todo item view
 */
@Composable
fun TodoRow(
    item: TodoItem,
    editorMode: Boolean,
    modifier: Modifier = Modifier,
    editItem: (TodoItem) -> Unit,
    updateItem: (TodoItem) -> Unit,
    deleteItem: (TodoItem) -> Unit,
) {
    val alpha by remember {
        mutableStateOf(Random.Default.nextDouble(0.3, 0.9)
            .toFloat())
    }

    Surface(modifier = Modifier.animateContentSize(animationSpec = TweenSpec(300))) {
        if (!editorMode) {
            Row(
                modifier = modifier
                    .clickable { editItem(item) }
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                horizontalArrangement = Arrangement.SpaceBetween  //横向均匀分布
            ) {
                Text(text = item.task)

                Icon(imageVector = item.icon.imageVector,
                    contentDescription =
                    stringResource(id = item.icon.contentDescription),
                    modifier = Modifier
                        .align(Alignment.CenterVertically)
                        .padding(end = 8.dp),
                    tint = LocalContentColor.current.copy(alpha)  //设置透明度为0.3-0.9随机
                )
            }
        } else {
            var currentIcon by remember {
                mutableStateOf(item.icon)
            }
            var inputText by remember {
                mutableStateOf(item.task)
            }
            Box(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
                Column {
                    BasicTextField(value = inputText, onValueChange = {
                        inputText = it
                    })
                    Spacer(modifier = Modifier.height(6.dp))
                    FlowLayout(itemsMargin = 5.dp, lineSpace = 1.dp) {
                        TodoItemTypeButton(iconItem = TodoIcon.Default,
                            selected = currentIcon == TodoIcon.Default) {
                            currentIcon = TodoIcon.Default
                        }
                        TodoItemTypeButton(iconItem = TodoIcon.Done,
                            selected = currentIcon == TodoIcon.Done) {
                            currentIcon = TodoIcon.Done
                        }
                        TodoItemTypeButton(iconItem = TodoIcon.Event,
                            selected = currentIcon == TodoIcon.Event) {
                            currentIcon = TodoIcon.Event
                        }
                        TodoItemTypeButton(iconItem = TodoIcon.Deleted,
                            selected = currentIcon == TodoIcon.Deleted) {
                            currentIcon = TodoIcon.Deleted
                        }
                    }
                }
                Row(modifier = Modifier.align(Alignment.CenterEnd)) {
                    TextButton(onClick = {
                        item.icon = currentIcon
                        item.task = inputText
                        updateItem(item)
                    }) {
                        Text(text = "\uD83D\uDCBE", textAlign = TextAlign.End)
                    }
                    TextButton(onClick = { deleteItem(item) }) {
                        Text(text = "×", textAlign = TextAlign.End)
                    }
                }
            }
        }
    }
}

/**
 * todo item新增widget
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun TodoItemAdder(editorMode: Boolean, modifier: Modifier = Modifier) {
    TodoItemInputBackground(editorMode = editorMode) {
        if (editorMode) {
            Text(modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(Alignment.CenterVertically)
                .padding(vertical = 12.dp),
                text = "Editing Item...",
                textAlign = TextAlign.Center)
        } else {
            var inputText by remember {
                mutableStateOf("")
            }

            var todoIcon by remember {
                mutableStateOf(TodoIcon.Default)
            }
            val viewModel = viewModel<TodoListViewModel>()

            val enterAnimation = remember {
                fadeIn(animationSpec = TweenSpec(300, easing = FastOutLinearInEasing))
            }
            val exitAnimation = remember {
                fadeOut(animationSpec = TweenSpec(100, easing = FastOutSlowInEasing))
            }

            val keyboardController = LocalSoftwareKeyboardController.current

            Column {
                Row(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
                    BasicTextField(value = inputText,
                        onValueChange = { inputText = it },
                        cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
                        singleLine = true,
                        keyboardActions = KeyboardActions(onDone = {
                            viewModel.addItem(TodoItem(inputText, todoIcon))
                            inputText = ""
                            todoIcon = TodoIcon.Default
                            keyboardController?.hide()
                        }),
                        keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
                        modifier = Modifier.weight(1f))
                    Spacer(modifier = Modifier.width(20.dp))
                    Button(onClick = {
                        viewModel.addItem(TodoItem(inputText, todoIcon))
                        inputText = ""
                        todoIcon = TodoIcon.Default
                        keyboardController?.hide()
                    }, enabled = inputText.isNotBlank()) {
                        Text(text = "Add")
                    }
                }
                AnimatedVisibility(
                    visible = inputText.isNotBlank(),
                    enter = enterAnimation,
                    exit = exitAnimation
                ) { //输入框中是否有内容决定是否展示
                    FlowLayout(itemsMargin = 16.dp, lineSpace = 4.dp,
                        modifier = Modifier.padding(6.dp)) {
                        TodoItemTypeButton(iconItem = TodoIcon.Default,
                            selected = todoIcon == TodoIcon.Default) {
                            todoIcon = TodoIcon.Default
                        }
                        TodoItemTypeButton(iconItem = TodoIcon.Done,
                            selected = todoIcon == TodoIcon.Done) {
                            todoIcon = TodoIcon.Done
                        }
                        TodoItemTypeButton(iconItem = TodoIcon.Event,
                            selected = todoIcon == TodoIcon.Event) {
                            todoIcon = TodoIcon.Event
                        }
                        TodoItemTypeButton(iconItem = TodoIcon.Deleted,
                            selected = todoIcon == TodoIcon.Deleted) {
                            todoIcon = TodoIcon.Deleted
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun TodoItemTypeButton(iconItem: TodoIcon, selected: Boolean, onSelected: () -> Unit) {
    Column {
        Icon(imageVector = iconItem.imageVector,
            contentDescription = stringResource(id = iconItem.contentDescription),
            tint = if (selected) MaterialTheme.colorScheme.primary else Color.Gray,
            modifier = Modifier.clickable { onSelected() }
        )
        Spacer(modifier = Modifier.height(5.dp))
        if (selected) {
            Box(modifier = Modifier
                .width(iconItem.imageVector.defaultWidth)
                .height(4.dp)
                .background(MaterialTheme.colorScheme.primary)
            )
        } else {
            Spacer(modifier = Modifier.height(4.dp))
        }
    }
}


@Composable
fun TodoItemInputBackground(
    modifier: Modifier = Modifier,
    editorMode: Boolean,
    content: @Composable RowScope.() -> Unit,
) {
    //背景色阴影变化state
    val animatedElevation by animateDpAsState(targetValue = if (editorMode) 0.dp else 1.dp,
        TweenSpec(300))

    Surface(color = MaterialTheme.colorScheme.surface.copy(0.5f),
        shape = RectangleShape,
        shadowElevation = animatedElevation) {
        Row(modifier =
        modifier.animateContentSize(animationSpec = TweenSpec(300)), //添加内容动画
            content = content
        )
    }
}












